<template>
  <div class="register-page">
    <div class="header">
      <img src="@/assets/logo.svg" alt="冷库自助下单系统" class="logo" />
      <h1>用户注册</h1>
      <p>创建您的冷库自助下单账户</p>
    </div>

    <van-form @submit="handleSubmit">
      <van-cell-group inset>

        <!-- 冷库名称 -->
        <van-field
          v-model="operatorTypeLabel2"
          readonly
          name="coldStorage"
          label="冷库名称"
          placeholder="请选择"
          input-align="right"
          is-link
          @click="showColdStorage = true"
          :rules="[{ required: true, message: '请选择冷库' }]"
        />

        <!-- 手机号输入 -->
        <van-field
          v-model="registerForm.phone"
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
          clearable
          :rules="phoneRules"
          @blur="validatePhone"
        />

        <!-- 短信验证码 -->
        <van-field
          v-model="registerForm.smsCode"
          label="短信验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              plain
              @click="sendSmsCode"
              :disabled="countdown > 0"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
            </van-button>
          </template>
        </van-field>

        <!-- 密码设置 -->
        <van-field
          v-model="registerForm.password"
          label="设置密码"
          :type="passwordVisible ? 'text' : 'password'"
          placeholder="6-20位字母和数字组合"
          clearable
          :rules="passwordRules"
        >
          <template #right-icon>
            <van-icon
              :name="passwordVisible ? 'eye-o' : 'closed-eye'"
              @click.stop="passwordVisible = !passwordVisible"
            />
          </template>
        </van-field>

        <!-- 确认密码 -->
        <van-field
          v-model="registerForm.confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="confirmPasswordRules"
        />

        <!-- 经营者类型 -->
        <van-field
          v-model="operatorTypeLabel"
          readonly
          name="picker"
          label="经营者类型"
          placeholder="请选择"
          input-align="right"
          is-link
          @click="showOperatorTypePicker = true"
          :rules="[{ required: true, message: '请选择经营者类型' }]"
        />

        <!-- 姓名/企业名称 -->
        <van-field
          v-model="registerForm.operatorName"
          label="经营者名称"
          :placeholder="`请输入${operatorTypeLabel}名称`"
          :rules="[{ required: true, message: `请输入${operatorTypeLabel}名称` }]"
        />

        <!-- 证件号码 -->
        <van-field
          v-model="registerForm.idNumber"
          :label="idNumberLabel"
          :placeholder="`请输入${idNumberLabel}`"
          :rules="idNumberRules"
        />

        <!-- 证件照片上传 -->
        <van-field
          name="idPhotos"
          label="证件照片"
          :rules="[{ validator: validatePhotos, message: '请上传证件照片' }]"
        >
          <template #input>
            <div class="photo-upload">
              <p class="upload-hint">请上传{{ operatorTypeLabel }}证件照片（最多3张）</p>
              <div class="photos-container">
                <div
                  v-for="(photo, index) in registerForm.idPhotos"
                  :key="index"
                  class="photo-item"
                >
                  <img :src="photo.url" class="photo-preview" />
                  <van-icon name="clear" class="delete-icon" @click.stop="removePhoto(index)" />
                </div>
                <van-uploader
                  v-if="registerForm.idPhotos.length < 3"
                  :after-read="addPhoto"
                  :max-count="3"
                  multiple
                >
                  <div class="upload-btn">
                    <van-icon name="plus" size="24" />
                  </div>
                </van-uploader>
              </div>
            </div>
          </template>
        </van-field>
      </van-cell-group>

      <div class="agreement">
        <van-checkbox
          v-model="agreed"
          icon-size="16"
          :rules="[{ required: true, message: '请阅读并同意协议' }]"
        >
          <div class="agreement-text">
            我已阅读并同意
            <router-link to="/agreement">《用户服务协议》</router-link>
            及
            <router-link to="/privacy">《隐私政策》</router-link>
          </div>
        </van-checkbox>
      </div>

      <div class="submit-btn">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="isRegistering"
          loading-text="注册中..."
        >
          提交注册
        </van-button>
      </div>
    </van-form>

    <div class="footer-text">
      已有账号？
      <router-link to="/login">立即登录</router-link>
    </div>

    <!-- 经营者类型选择器 -->
    <van-popup v-model:show="showOperatorTypePicker" round position="bottom">
      <van-picker
        :columns="operatorTypes"
        @cancel="showOperatorTypePicker = false"
        @confirm="onOperatorTypeConfirm"
      />
    </van-popup>
    <!-- 冷库类型选择器 -->
    <van-popup v-model:show="showColdStorage" round position="bottom">
      <van-picker
        :columns="operatorTypes2"
        @cancel="showColdStorage = false"
        @confirm="onOperatorTypeConfirm2"
      />
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Notify } from 'vant'
import type { UploaderFileListItem } from 'vant'
import { idCardRules, businessLicenseRules } from '../utils/validator'
import { useUserStore } from '../stores/user'

interface RegisterForm {
  coldStorage: string
  phone: string
  smsCode: string
  password: string
  confirmPassword: string
  operatorType: 'individual' | 'enterprise'
  operatorName: string
  idNumber: string
  idPhotos: { url: string; file?: File }[]
}

interface OperatorType {
  text: string
  value: 'individual' | 'enterprise'
}
interface OperatorType2 {
  text: string,
  value: string
}

export default defineComponent({
  name: 'RegisterPage',

  setup() {
    const router = useRouter()
    const userStore = useUserStore()

    // 注册表单数据
    const registerForm = reactive<RegisterForm>({
      coldStorage: '',
      phone: '',
      smsCode: '',
      password: '',
      confirmPassword: '',
      operatorType: 'individual',
      operatorName: '',
      idNumber: '',
      idPhotos: [],
    })

    // 状态变量
    const isRegistering = ref(false)
    const passwordVisible = ref(false)
    const showOperatorTypePicker = ref(false)
    const showColdStorage = ref(false)
    const countdown = ref(0)
    const agreed = ref(true)

    // 验证码倒计时定时器
    let countdownTimer: ReturnType<typeof setTimeout> | null = null

    // 经营者类型选项
    const operatorTypes: OperatorType[] = [
      { text: '个人', value: 'individual' },
      { text: '企业', value: 'enterprise' },
    ]
    // 冷库类型选项
    const operatorTypes2: OperatorType2[] = [
      { text: '冷库1', value: '001' },
      { text: '冷库2', value: '002' },
    ]

    // 计算属性
    const operatorTypeLabel = computed(() => {
      return registerForm.operatorType === 'individual' ? '个人' : '企业'
    })
    const operatorTypeLabel2 = computed(() => {
      console.log(operatorTypes2.values, 'ddd', operatorTypes2)
      const item = operatorTypes2.find(v => v.value === registerForm.coldStorage)
      console.log('eeeeeeeeeeeeee', item)
      return item?.text
      // return registerForm.coldStorage === 'individual' ? '个人' : '企业'
    })

    const idNumberLabel = computed(() => {
      return registerForm.operatorType === 'individual' ? '身份证号' : '统一社会信用代码'
    })

    // 验证规则
    const phoneRules = [
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
    ]

    const passwordRules = [
      { required: true, message: '请输入密码' },
      { min: 6, max: 20, message: '密码长度在6-20位之间' },
      { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码需包含字母和数字' },
    ]

    const confirmPasswordRules = [
      { required: true, message: '请再次输入密码' },
      {
        validator: (val: string) => val === registerForm.password,
        message: '两次密码输入不一致',
      },
    ]

    const idNumberRules = computed(() => {
      return registerForm.operatorType === 'individual' ? idCardRules : businessLicenseRules
    })

    // 验证表单照片
    const validatePhotos = () => {
      return registerForm.idPhotos.length > 0
    }

    // 手机号验证
    const validatePhone = () => {
      return /^1[3-9]\d{9}$/.test(registerForm.phone)
    }

    // 发送短信验证码
    const sendSmsCode = async () => {
      if (!validatePhone()) {
        Notify({ type: 'danger', message: '请输入有效的手机号' })
        return
      }

      try {
        // 调用发送短信API
        // await userStore.sendSmsCode(registerForm.phone, 'register')
        registerForm.smsCode = ' 123456'

        // 开始倒计时
        countdown.value = 60
        if (countdownTimer) clearInterval(countdownTimer)

        countdownTimer = setInterval(() => {
          countdown.value--
          if (countdown.value <= 0 && countdownTimer) {
            clearInterval(countdownTimer)
            countdownTimer = null
          }
        }, 1000)

        Toast('验证码已发送')
      } catch (error) {
        Notify({
          type: 'danger',
          message: error instanceof Error ? error.message : '发送验证码失败',
        })
      }
    }

    // 添加照片
    const addPhoto = (file: UploaderFileListItem | UploaderFileListItem[]) => {
      const files = Array.isArray(file) ? file : [file]

      if (registerForm.idPhotos.length + files.length > 3) {
        Notify({ type: 'danger', message: '最多上传3张照片' })
        return
      }

      files.forEach((f) => {
        if (f.file) {
          registerForm.idPhotos.push({
            url: URL.createObjectURL(f.file),
            file: f.file,
          })
        }
      })
    }

    // 移除照片
    const removePhoto = (index: number) => {
      registerForm.idPhotos.splice(index, 1)
    }

    // 选择经营者类型
    const onOperatorTypeConfirm = (value: OperatorType) => {
      registerForm.operatorType = value.value
      registerForm.operatorName = ''
      registerForm.idNumber = ''
      showOperatorTypePicker.value = false
    }
    // 选择经营者类型
    const onOperatorTypeConfirm2 = (value: OperatorType) => {
      registerForm.coldStorage = value.value
      showColdStorage.value = false
    }

    // 提交注册
    const handleSubmit = async () => {
      if (!agreed.value) {
        Notify({ type: 'danger', message: '请同意用户协议和隐私政策' })
        return
      }

      isRegistering.value = true

      try {
        // 准备表单数据
        const formData = new FormData()
        formData.append('phone', registerForm.phone)
        formData.append('smsCode', registerForm.smsCode)
        formData.append('password', registerForm.password)
        formData.append('operatorType', registerForm.operatorType)
        formData.append('operatorName', registerForm.operatorName)
        formData.append('idNumber', registerForm.idNumber)

        // 添加照片文件
        registerForm.idPhotos.forEach((photo) => {
          if (photo.file) {
            formData.append(`idPhotos`, photo.file)
          }
        })

        console.log('ggggggggggggggg', formData)

        // 调用注册API
        const res =  await userStore.register(formData)
        console.log('fffffffffff', res)
        if (res) {
          Toast({ message: '注册成功', icon: 'success' })
          // 注册成功后跳转到首页
          setTimeout(() => {
            router.push('/')
          }, 1000)
        }



      } catch (error) {
        Notify({
          type: 'danger',
          message: error instanceof Error ? error.message : '注册失败，请稍后重试',
        })
      } finally {
        isRegistering.value = false
      }
    }

    return {
      registerForm,
      isRegistering,
      passwordVisible,
      showOperatorTypePicker,
      showColdStorage,
      countdown,
      agreed,
      operatorTypes,
      operatorTypes2,
      operatorTypeLabel,
      operatorTypeLabel2,
      idNumberLabel,
      phoneRules,
      passwordRules,
      confirmPasswordRules,
      idNumberRules,
      validatePhone,
      validatePhotos,
      sendSmsCode,
      addPhoto,
      removePhoto,
      onOperatorTypeConfirm,
      onOperatorTypeConfirm2,
      handleSubmit,
    }
  },
})
</script>

<style scoped lang="scss">
.register-page {
  padding: 20px 16px 40px;
  min-height: 100vh;
  background-color: #fff;
}

.header {
  text-align: center;
  margin-bottom: 30px;

  .logo {
    width: 80px;
    height: 80px;
    margin: 0 auto 15px;
  }

  h1 {
    font-size: 24px;
    color: #333;
    font-weight: 600;
    margin-bottom: 8px;
  }

  p {
    font-size: 14px;
    color: #999;
  }
}

.agreement {
  padding: 15px 16px 5px;
  font-size: 12px;

  .agreement-text {
    padding-left: 5px;
    color: #666;

    a {
      color: #1989fa;
    }
  }
}

.submit-btn {
  margin: 25px 16px 15px;
}

.footer-text {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 15px;

  a {
    color: #1989fa;
  }
}

.photo-upload {
  width: 100%;

  .upload-hint {
    font-size: 12px;
    color: #969799;
    margin: 5px 0 10px;
  }

  .photos-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .photo-item {
      position: relative;
      width: 80px;
      height: 80px;

      .photo-preview {
        width: 100%;
        height: 100%;
        border-radius: 8px;
        object-fit: cover;
        border: 1px solid #eee;
      }

      .delete-icon {
        position: absolute;
        top: -8px;
        right: -8px;
        color: #f5222d;
        background: #fff;
        border-radius: 50%;
        font-size: 16px;
        padding: 2px;
      }
    }

    .upload-btn {
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #f7f8fa;
      border-radius: 8px;
      border: 1px dashed #c8c9cc;
      color: #969799;
      box-sizing: border-box;
    }
  }
}
</style>
